package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.repository.StrategyTemplateRepository;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.vo.StatsResult;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class StrategySearchServiceImpl implements IStrategySearchService {

    @Autowired
    private StrategyTemplateRepository repository;

    public List<Map<String, Object>> themeCommend() {
        //步骤  :有一个集合.里面使用map封装主题名字和目的地的关系.(攻略domain)
        List<Map<String, Object>> list = new ArrayList<>();
        //        1.根据主题做桶聚合
        List<StatsResult> tss = groupCondition("themeId", "themeName", 0);
        for (StatsResult t : tss) {
            Map<String, Object> map = new HashMap<>();
            //遍历获取主题名称.
            map.put("themeName", t.getName());
            //2.根据主题的id查询所有攻略.
            Set<StatsResult> set = new HashSet<>();
            List<StrategyTemplate> templates = repository.findByThemeId(t.getId(), null).getContent();
            //        遍历所有攻略
            for (StrategyTemplate s : templates) {
                //攻略获取目的地id目的地名字.
                Long destId = s.getDestId();
                String destName = s.getDestName();
                //        之后填充到Set结合去重.
                set.add(new StatsResult(destId, destName, null));
            }
            //3.填充到map中.
            map.put("dests", set);
            //4.添加到集合中.
            list.add(map);
        }
        return list;
    }

    public List<StrategyTemplate> listByDestName(String name) {
        return repository.findByDestName(name);
    }


    public void save(StrategyTemplate template) {
        repository.save(template);
    }

    public List<StatsResult> listCondition(int condition) {
        String id = null;
        String name = null;
        switch (condition) {
            case SearchQueryObject.CONDITION_UNABROAD:
                //中国
                id = "provinceId";
                name = "provinceName";
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                //外国
                id = "countryId";
                name = "countryName";

                break;
            case SearchQueryObject.CONDITION_THEME:
                //
                id = "themeId";
                name = "themeName";
                break;
        }
        return groupCondition(id, name, condition);

    }

    public Page<StrategyTemplate> query(SearchQueryObject qo) {
        Page<StrategyTemplate> page = null;
        switch (qo.getType()) {
            //根据类型和id(TypeValue)
            case SearchQueryObject.CONDITION_UNABROAD:
                page = repository.findByProvinceId(qo.getTypeValue(), qo.getPageable());
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                page = repository.findByCountryId(qo.getTypeValue(), qo.getPageable());

                break;
            case SearchQueryObject.CONDITION_THEME:
                page = repository.findByThemeId(qo.getTypeValue(), qo.getPageable());

                break;
            default:
                page = repository.findAll(qo.getPageable());
        }

        return page;
    }


//   桶聚合多维度查询

    private List<StatsResult> groupCondition(String id, String name, int condition) {
        String groupType = "groupType";
        String idField = "id";
        String nameField = "name";

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withPageable(PageRequest.of(0, 1));
        switch (condition) {
            case SearchQueryObject.CONDITION_UNABROAD:
                //CONDITION_UNABROAD->排除非中国数据
                builder.withQuery(QueryBuilders.termQuery("countryId", StatsResult.CHINA_ID));
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                //CONDITION_ABROAD->排除中国数据
                builder.withQuery(
                        QueryBuilders.boolQuery()
                                .mustNot(
                                        QueryBuilders.termQuery("countryId", StatsResult.CHINA_ID)
                                )
                );
                break;
        }

        //多维度桶聚合条件
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();

        sources.add(new TermsValuesSourceBuilder(idField).field(id));
        sources.add(new TermsValuesSourceBuilder(nameField).field(name));

        CompositeAggregationBuilder group = new CompositeAggregationBuilder(groupType, sources);

        builder.addAggregation(group);
        AggregatedPage<StrategyTemplate> page = (AggregatedPage<StrategyTemplate>) repository.search(builder.build());

        //拿到分组结果
        CompositeAggregation aggs = (CompositeAggregation) page.getAggregation(groupType);

        List<StatsResult> list = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : aggs.getBuckets()) {
            Map<String, Object> key = bucket.getKey();
            Object idValue = key.get(idField);
            Object nameValue = key.get(nameField);
            long count = bucket.getDocCount();
            list.add(new StatsResult(Long.parseLong(idValue.toString()), nameValue.toString(), count));
        }
        return list;
    }

}
